package utils;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import java.io.File;

import common.Constant;
import common.Variable;
import https.DownLoadFileController;
import view.MyConfirmDialog;

/**
 * Created by Administrator on 2017/6/16.
 * 版本更新工具
 */

public class UpdateUtils {
    private static UpdateUtils instance;

    public static UpdateUtils getInstance() {
        if (instance == null) {
            instance = new UpdateUtils();
        }
        return instance;
    }

    public void updateNewVersion(final Context context) {
        final String apkName = "jinzhaoshengxue"+SPUtils.getSharedPreferences().getString(Constant.LAST_VERSION, "v1.3.0") +".apk";
        if (Variable.IS_NEW_VERSION) {
            if (!getApk(apkName)) {
                //不存在最新安装包时
                MyConfirmDialog myConfirmDialog = new MyConfirmDialog(context, "检测到新的版本，是否下载？", "是", "否");
                myConfirmDialog.setConfirmListener(() -> DownLoadFileController.getInstance().downLoad(context, Constant.UPDATE_URL, null, apkName, 0));
                myConfirmDialog.show();
            }
            else{
                //存在最新安装包
                MyConfirmDialog myConfirmDialog = new MyConfirmDialog(context, "已经下载最新安装包，是否安装？", "是", "否");
                myConfirmDialog.setConfirmListener(() -> {
                    Intent i = new Intent();
                    Uri uri = Uri.fromFile(new File(Constant.APK_DIR + File.separator + apkName));
                    // 创建Intent意图
                    i.setAction(Intent.ACTION_VIEW);
                    // 设置Uri和类型
                    i.setDataAndType(uri, "application/vnd.android.package-archive");
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    // 执行意图进行安装
                    context.startActivity(i);
                });
                myConfirmDialog.show();
            }
        }
    }


    private boolean getApk(String apkName) {
        //检测本地是否有安装包
        File dir = new File(Constant.APK_DIR);
        if (dir.exists()) {
            if (dir.isDirectory()) {
                File[] files = dir.listFiles();
                for (File f : files) {
                    if (f.getName().equals(apkName)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
